//
//  StaffListController.m
//  ios-supplier
//
//  Created by feynmanyuan on 15/4/17.
//  Copyright (c) 2015年 feynmanyuan. All rights reserved.
//

#import "StaffListController.h"
#import "StaffCell.h"
#import "JFBStaffDS.h"

#import "JFBLoadingAnimation.h"

@interface StaffListController ()<UIAlertViewDelegate,UIGestureRecognizerDelegate> {
    BOOL _editStatusEnable;
    NSUInteger _currentStaffID;
    NSUInteger _willDeleteStaffID;
}
- (IBAction)staffEditAction:(id)sender;
@property (nonatomic, strong) JFBStaffDS *defaultStaffDS;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *staffTarBarItem;

@property (strong, nonatomic) IBOutlet UITableView *tableViewController;


@property (nonatomic, strong) NSMutableArray *staffs;
#define screen_Width [UIScreen mainScreen].bounds.size.width
#define screen_Height [UIScreen mainScreen].bounds.size.height
@end

@implementation StaffListController
-(void)viewWillAppear:(BOOL)animated{
    [self reload:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.staffs = [@[] mutableCopy];
    
    _editStatusEnable = false;
    
    self.tableViewController.frame = CGRectMake(0, 0, screen_Width, screen_Height);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(staffListBtnClick:) name:@"staffListBtnClick" object:nil];

//    [self reload:nil];
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [self.navigationItem setLeftBarButtonItem: [self createBackView]];
}


- (UIBarButtonItem *)createBackView
{
    UIButton *leftButtonItem = [UIButton buttonWithType:UIButtonTypeCustom];
    
    leftButtonItem.frame = CGRectMake(0, 0, 11, 20);
    
    [leftButtonItem setBackgroundImage:[UIImage imageNamed:@"icon-Back"] forState:UIControlStateNormal];
    
    [leftButtonItem setImageEdgeInsets: UIEdgeInsetsMake((19 - 11) / 2, 0, (19 - 11) / 2, 0)];
    
    [leftButtonItem addTarget:self action:@selector(leftButtonItemClicked) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:leftButtonItem];
    
    return item;
}

-(void)leftButtonItemClicked
{
    [self.navigationController popViewControllerAnimated:YES];
    self.navigationController.navigationBar.hidden = YES;
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if( buttonIndex == 1 ) {
        [JFBStaffDS deleteStaff:^(BOOL isSuccess, NSError *error) {
            if( isSuccess ) {
                //清除数据，重新加载
                if( self.defaultStaffDS && self.defaultStaffDS.Id == _willDeleteStaffID ) {
                    self.defaultStaffDS = nil;
                } else {
                    NSMutableArray *t = [@[] mutableCopy];
                    for(JFBStaffDS *ds in self.staffs) {
                        if( ds.Id != _willDeleteStaffID ) {
                            [t addObject:ds];
                        }
                    }
                    self.staffs = t;
                }
                [self.tableViewController reloadData];
            }
        } staffID:_willDeleteStaffID];
    }
}

- (void)staffListBtnClick:(NSNotification *)notification {
    NSUInteger staffID = [[notification.userInfo objectForKey:@"staffID"] intValue];
    NSLog(@".....................%ld",staffID);
    _willDeleteStaffID = staffID;
    [JFBUIAnimation alertSure:@"确定删除该快递员?" delegate:self];
    [self reload:nil];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
//    if( [segue.identifier isEqualToString:@"editStaffIdentifier"] && _currentStaffID != 0) {
//        JFBStaffDS *cds;
//        if( self.defaultStaffDS.Id == _currentStaffID ) {
//            cds = self.defaultStaffDS;
//        } else {
//            for(JFBStaffDS *ds in self.staffs) {
//                if( ds.Id == _currentStaffID ) {
//                    cds = ds;
//                    break;
//                }
//            }
//        }
//        StaffEditController *ctrl = (StaffEditController*)segue.destinationViewController;
//        ctrl.delegate = self;
//        ctrl.hidesBottomBarWhenPushed = true;
//        ctrl.staff = cds;
//    } else {
//        StaffEditController *ctrl = (StaffEditController*)segue.destinationViewController;
//        ctrl.delegate = self;
//        ctrl.hidesBottomBarWhenPushed = true;
//        ctrl.staff = nil;
//    }
    if ([segue.identifier isEqualToString:@"editStaffIdentifier"]&&_currentStaffID != 0) {
        JFBStaffDS *cds;
        if( self.defaultStaffDS.Id == _currentStaffID ) {
            cds = self.defaultStaffDS;
        } else {
            for(JFBStaffDS *ds in self.staffs) {
                if( ds.Id == _currentStaffID ) {
                    cds = ds;
                    break;
                }
            }
        }
        StaffEditController *ctrl = (StaffEditController*)segue.destinationViewController;
        ctrl.delegate = self;
        ctrl.hidesBottomBarWhenPushed = true;
        ctrl.staff = cds;
    }else {
        StaffEditController *ctrl = (StaffEditController*)segue.destinationViewController;
        ctrl.delegate = self;
        ctrl.hidesBottomBarWhenPushed = true;
        ctrl.staff = nil;
    }
}

-(void)reload{
    [self reload:nil];
}

- (void)reload:(__unused id)sender {
    JFBLoadingAnimation * animation = [[JFBLoadingAnimation alloc] init:self.tableView];
    [JFBStaffDS loadStaffList:^(NSArray *staffList, NSError *error) {
        [animation stop];
        self.staffs = [@[] mutableCopy];
        self.defaultStaffDS = nil;
        for( JFBStaffDS *ds in staffList ) {
            [self.staffs addObject:ds];
        }
        [self.tableView reloadData];
    } pager:nil];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return  1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.staffs.count == 1) {
        return 1;
    }else
    return  self.staffs.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    StaffCell *cell = [tableView dequeueReusableCellWithIdentifier:@"staffIdentifier" forIndexPath:indexPath];
    JFBStaffDS *ds = self.staffs[indexPath.row];
    cell.editStatusEnable = _editStatusEnable;
    cell.staff = ds;
    cell.editButton.tag = 200+indexPath.row;
    [cell.editButton addTarget:self action:@selector(editButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}
-(void)editButtonClick:(UIButton *)button {
    JFBStaffDS *ds = self.staffs[button.tag-200];
    _currentStaffID = ds.Id;
    [self performSegueWithIdentifier:@"editStaffIdentifier" sender:self];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    JFBStaffDS *ds = self.staffs[indexPath.row];
    _currentStaffID = ds.Id;
    [self performSegueWithIdentifier:@"editStaffIdentifier" sender:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)staffEditAction:(id)sender {
    _currentStaffID = 0;
    [self performSegueWithIdentifier:@"editStaffIdentifier" sender:self];
}

-(BOOL)checkPhoneNumberRepeat:(NSString *)phoneString
{
    for(JFBStaffDS *ds in self.staffs) {
        if ([ds.telephone isEqualToString: phoneString]) {
            return NO;
        }
    }
    return YES;
}


@end
